<?php

namespace App\Models;

use Cache;

class XcxTpl extends BaseModel
{

    public $redisTable = 'access_token';

    public function __construct()
    {
        parent::__construct();
        if (request('aid')) {
            $wechatSet = new WechatSet();
            $wechat = $wechatSet->_redisGetOneByAid(1);
            $this->app_id = $wechat['xcx_app_id'];
            $this->app_secret = $wechat['xcx_app_secret'];
        }
    }


    public function newOrderMsg($sid, $orderId, $formId)
    {
//        模板ID
//        YZffmoTLsEkriah7v5QeK-Q9e-P8QnNd6VLCzNuQEv8复制
//标题
//新订单通知
//关键词
//下单时间
//{{keyword1.DATA}}
//商品名称
//{{keyword2.DATA}}
//数量
//{{keyword3.DATA}}
//收货地址
//{{keyword4.DATA}}
//备注
//{{keyword5.DATA}}

        $worker = new Worker();
        $workers = $worker->_getList(['shop_id' => $sid], 'xcx_openid as openid')->toArray();
        if (!$workers) {
            tolog('发送失败，该店铺没有送水工');
            return false;
        }
        $tousers = array_column($workers, 'openid');
        $order = new Order();
        $orderInfo = $order->_getOneById($orderId);
        if (!$orderInfo) {
            return false;
        }
        if ($order['dispatch'] != 0) {
            return false;
        }
        $orderGoods = new OrderGoods();
        $orderGoodsList = $orderGoods->_getList(['order_id' => $orderId])->toArray();
        $goodsName = $orderGoodsList[0]['goods_name'] . (count($orderGoodsList) > 1 ? '等' : '');
        $data = [
            'keyword1' => ['value' => date('Y-m-d H:i:s'), 'color' => ''],
            'keyword2' => ['value' => $goodsName, 'color' => ''],
            'keyword3' => ['value' => $orderInfo['bucket_num'], 'color' => ''],
            'keyword4' => ['value' => $orderInfo['buyer_address'], 'color' => ''],
            'keyword5' => ['value' => $orderInfo['description'], 'color' => ''],
        ];
        $tmplId = 'YZffmoTLsEkriah7v5QeK-Q9e-P8QnNd6VLCzNuQEv8';
        $this->send_msg($data, $tousers, $tmplId, $formId);
    }

    public function paisongMsg($adminId,$orderId)
    {
//        模板ID
//jahJliZ9E1h8Qjs2k0nuGZpbNCLcszxqZEewbzupDD0复制
//标题
//订单配送通知
//关键词
//下单时间
//{{keyword1.DATA}}
//配送员
//{{keyword2.DATA}}
//配送员电话
//{{keyword3.DATA}}
        $wechatSet = new WechatSet();
        $wechatInfo = $wechatSet->_redisGetOneByAid(1);
        if (!isset($wechatInfo['xcx_notice_send_id'])) {
            return true;
        }
        if (!$wechatInfo['xcx_notice_send_id']) {
            return true;
        }
        $order = new Order();
        $orderInfo = $order->_getOneById($orderId,'buyer_id,worker_id,addtime');
        if (!$orderInfo) {
            return false;
        }
        $member = new Member();
        $formId = $member->_redisGetFormId($orderInfo['buyer_id']);
        if (!$formId) {
            return false;
        }
        $memberInfo = $member->_redisGetOneByMid($orderInfo['buyer_id']);
        $tousers = $memberInfo['xcx_openid'];
        if (!$tousers) {
            return false;
        }
        $worker = new Worker();
        $workerInfo = $worker->_redisGetOneByWid($orderInfo['worker_id']);
        $data = [
            'keyword1' => ['value' => date('Y-m-d H:i',$orderInfo['addtime'] ), 'color' => ''],
            'keyword2' => ['value' => $workerInfo['name'], 'color' => ''],
            'keyword3' => ['value' => $workerInfo['mobile'], 'color' => ''],
        ];
        $tmplId = $wechatInfo['xcx_notice_send_id'];
        $this->send_msg($data, $tousers, $tmplId, $formId);
    }

    public function completeMsg($adminId,$orderId)
    {
//        模板ID
//DC71YXujp7jN-wUo7O445BuYQOJnvmcoAJPofGoIuP0复制
//标题
//配送完成通知
//关键词
//送达时间
//{{keyword1.DATA}}
//商品名称
//{{keyword2.DATA}}
//商品数量
//{{keyword3.DATA}}
//回桶数量
//{{keyword4.DATA}}
//水票余额
//{{keyword5.DATA}}
        $wechatSet = new WechatSet();
        $wechatInfo = $wechatSet->_redisGetOneByAid(1);
        if (!isset($wechatInfo['xcx_notice_send_id'])) {
            return true;
        }
        if (!$wechatInfo['xcx_notice_send_id']) {
            return true;
        }
        $order = new Order();
        $orderInfo = $order->_getOneById($orderId,'buyer_id,worker_id,addtime');
        if (!$orderInfo) {
            return false;
        }
        $member = new Member();
        $formId = $member->_redisGetFormId($orderInfo['buyer_id']);
        if (!$formId) {
            return false;
        }
        $memberInfo = $member->_redisGetOneByMid($orderInfo['buyer_id']);
        $tousers = $memberInfo['xcx_openid'];
        if (!$tousers) {
            return false;
        }
        $orderGoods = new OrderGoods();
        $orderGoodsList = $orderGoods->_getList(['order_id' => $orderId])->toArray();
        $goodsName = $orderGoodsList[0]['goods_name'] . (count($orderGoodsList) > 1 ? '等' : '');
        $member = new Member();
        $memberInfo = $member->_getOneById($orderInfo['buyer_id'], 'xcx_openid');
        $tousers = $memberInfo['xcx_openid'];
        $data = [
            'keyword1' => ['value' => $orderInfo['updated_at'], 'color' => ''],
            'keyword2' => ['value' => $goodsName, 'color' => ''],
            'keyword3' => ['value' => $orderInfo['bucket_num'], 'color' => ''],
            'keyword4' => ['value' => $orderInfo['back_bucket_num'], 'color' => ''],
            'keyword5' => ['value' => $memberInfo['total_waterbill_num'], 'color' => ''],
        ];
        $tmplId = 'DC71YXujp7jN-wUo7O445BuYQOJnvmcoAJPofGoIuP0';
        $this->send_msg($data, $tousers, $tmplId, $formId);
    }


    public function send_msg($data, $tousers, $tmplId, $formId, $page = '')
    {
//        tolog([$data, $tousers, $tmplId, $formId]);
//        $access_token = $this->getAccessToken();
        $access_token = $this->_redisGetAccessToken();
//        tolog($access_token);
        $url = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=' . $access_token;
        $msgData['touser'] = $tousers;
        $msgData['template_id'] = $tmplId;
        $msgData['page'] = $page;  //点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,该字段不填则模板无跳转。
        $msgData['form_id'] = $formId;
        $msgData['data'] = $data;                        //模板内容，不填则下发空模板
        $msgData['emphasis_keyword'] = '';    //模板需要放大的关键词，不填则默认无放大
        if (is_array($tousers)) {
            foreach ($tousers as $v) {
                $msgData['touser'] = $v;
//                tolog($msgData);
                $res = $this->https_curl_json($url, $msgData, 'json');
//                tolog('res---');
//                tolog($res);
                if (!$res) {
//                    tolog('发送消息，获取access_token失败');
                    return false;
                }
            }
            return true;
        }
//        tolog($msgData);
        $res = $this->https_curl_json($url, $msgData, 'json');
//        tolog('fasong');
//        tolog($res);
        if (!$res) {
//            tolog('发送消息，获取access_token失败');
            return false;
        }
//        tolog('发送消息成功');
        return true;
    }

    /* 发送json格式的数据，到api接口 -xzz0704  */
    public function https_curl_json($url, $data, $type)
    {
        if ($type == 'json') {//json $_POST=json_decode(file_get_contents('php://input'), TRUE);
            $headers = array("Content-type: application/json;charset=UTF-8", "Accept: application/json", "Cache-Control: no-cache", "Pragma: no-cache");
            $data = json_encode($data);
        }
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        $output = curl_exec($curl);
        if (curl_errno($curl)) {
            $this->error = 'Errno :' . curl_error($curl);
            return false;
        }
        curl_close($curl);
        return $output;
    }

    // 调用微信api，获取access_token，有效期7200s
    public function getAccessToken()
    {
        /* 在有效期，直接返回access_token */
        $access_token = Cache::get('access_token');
        $key = $this->app_id;
        $this->redis->get($key);
        if (!$access_token) {
            //不在有效期，重新发送请求，获取access_token
            $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $this->app_id . '&secret=' . $this->app_secret;
            $result = file_get_contents($url);
            $res = json_decode($result, true);   //json字符串转数组
            if (!$res) {
//                tolog('发送消息，获取access_token失败');
                $this->error = '发送消息，获取access_token失败';
                return false;
            }
            $access_token = $res['access_token'];
            Cache::put('access_token', $access_token, 7100);
        }
        return $access_token;
    }

    public function _redisGetAccessToken()
    {
        $table = $this->redisTable;
        $key = $this->app_id;
        if ($this->redis->hexists($table, $key)) {
            $res = $this->redis->hmget($table, $key);
            if ($res) {
                $result = unserialize($res[0]);
                if (time() - $result['addtime'] < 7180) {
                    return $result['access_token'];
                }
            }
        }
        //不在有效期，重新发送请求，获取access_token
        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $this->app_id . '&secret=' . $this->app_secret;
        $result = file_get_contents($url);
        $res = json_decode($result, true);   //json字符串转数组
        if ($res) {
            $data['access_token'] = $res['access_token'];
            $data['addtime'] = time();
            $this->redis->hmset($table, [$key => serialize($data)]);
            return $res['access_token'];
        }
        return false;
    }

}